from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from project.models import UserInDB
from project.user.schemas import UserCreate
from project.user.util import get_password_hash, verify_password


async def create_user(db: AsyncSession, user: UserCreate):
    """
    创建用户
    :param db:
    :param user:
    :return:
    """
    db_user: UserInDB = await get_user_by_name(db, user.username)

    if db_user:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"用户名{user.username}已存在"
        )
    try:
        new_user = user.model_copy()
        new_user.password = get_password_hash(user.password)
        db_user = UserInDB(**new_user.model_dump())
        db.add(db_user)

        await db.flush()

        return db_user

    except Exception as e:
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"创建用户失败，失败原因：{str(e)}"
        )


async def get_user_by_name(db: AsyncSession, username: str):
    """
    通过用户名获取处于活跃状态的用户
    :param db:
    :param username:
    :return: 如果找到用户，返回用户对象；否则返回 None
    """
    query = select(UserInDB).filter(UserInDB.username == username, UserInDB.state == True)
    user = await db.execute(query)
    db_user: UserInDB = user.scalar_one_or_none()
    return db_user


async def get_user_by_id(db: AsyncSession, id: str):
    """
    通过id获取用户
    :param db:
    :param id:
    :return:
    """
    query = select(UserInDB).filter(UserInDB.id == id)

    user = await db.execute(query)
    db_user = user.scalar_one_or_none()
    return db_user


async def authenticate_user(db: AsyncSession, username: str, password: str):
    """
    验证用户
    :param db:
    :param username:
    :param password:
    :return:
    """
    user = await get_user_by_name(db, username)
    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user
